import React from 'react';
import { Card, Row, Col } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import AddModal from './components/AddModal';
import Search from './components/Search';
import OrganizationTree from '@/components/OrganizationTree';
import { pageList, del } from '@/services/School';
import columns from './columns';

class School extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      params: {},
      dataSource: []
    }
    this.proTableRef = React.createRef();
  }

  /* 获取数据列表 */
  getPageList = async (currentParams) => {
    try {
      const params = this.state.params;
      const res = await pageList({
        ...params,
        ...currentParams
      })
      this.setState({ dataSource: res.data });
      return {
        data: res.data,
        total: res.totalSize,
        success: true
      }
    } catch (e) {
      console.error(e)
    }
  }

  /* 监听查询事件 */
  onSearch = (data) => {
    const params = this.state.params;
    this.setState({ params: { ...params, ...data } });
    this.proTableRef.current.reload();
  }

  /* 刷新事件 */
  onReload = () => {
    this.setState({ params: {} });
    this.proTableRef.current.reload();
  }

  /* 监听删除项 */
  onDel = async (id) => {
    const dataSource = this.state.dataSource;
    this.setState({
      dataSource: dataSource.filter(function (item) {
        return item.id !== id
      })
    })
    await del(id);
    // this.proTableRef.current.reload();
  }

  /* 监听机构选择 */
  onUnitSelect = async (id) => {
    // await this.getDetail(id)
    const params = this.state.params;
    params.parentId = id;
    this.setState({ params });
    this.getPageList();
  }

  render() {
    const { onSearch, onReload, onDel, onUnitSelect, proTableRef } = this;
    const { params, dataSource } = this.state;
    return (
      <PageContainer>
        <Row gutter={16}>
          <Col span={4}>
            <OrganizationTree select={onUnitSelect} />
          </Col>
          <Col span={20}>
            <Card
              bodyStyle={{ paddingTop: 30, paddingBottom: 0 }}
              title="学校列表"
              bordered={false}>
              <Search search={onSearch} reset={onReload} />
            </Card>
            <ProTable
              // pagination={{ pageSizeOptions: [1, 2, 3] }}
              actionRef={proTableRef}
              rowKey='id'
              manualRequest={true}
              headerTitle={<AddModal add={onReload}>新增学校</AddModal>}
              search={false}
              scroll={{ x: true }}
              dataSource={dataSource}
              columns={columns(onDel)}
              request={this.getPageList} />
          </Col>
        </Row>
      </PageContainer>
    );
  }
}

export default School;
